'use strict';
import Command from "@breeze-cli-dev/command";
import log from "@breeze-cli-dev/log";
// import fs from 'fs';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import inquirer from 'inquirer';
import fse from 'fs-extra';
import Package from "@breeze-cli-dev/package";
import { valid  } from 'semver'
// 引入加载动画库
import ora from 'ora';
// 引入测试模版参数
import { npmTemplate } from "../config/config.js";
// function init(projectName, cmdObj) {
//  console.log('init命令执行了', projectName, cmdObj, process.env.CLI_TARGET_PATH);
// }
const TYPE_PROJECT = 'project';
const TYPE_COMPONENT = 'component';
const TEMPLATE_TYPE_NORMAL = 'normal'; // 普通模版
const TEMPLATE_TYPE_CUSTOM = 'custom'; // 自定义模版
class initCommand extends Command {
  init() {
    this.projectName = this._argv[0] || '';
    this.force = !!this.cdm.opts().force;
    log.verbose('projectName', this.projectName);
    log.verbose('force', this.force);
  }
  async exec() {
    try {
      // 判断当前目录是否为空
      const projectInfo = await this.prepare()
      if (projectInfo) {
       this.projectInfo = projectInfo;
      //  console.log('projectInfo', projectInfo);
      //  console.log('npmTemplateList', this.npmTemplateList);
      await this.downloadTemplate(); // 下载模版
        // 安装模版
      await this.installTemplate(); // 安装模版  
      }
    } catch (error) {
      log.error(error.message);
    }
    console.log('initCommand exec方法执行了');
  }
  async installTemplate() {
    log.verbose('templateInfo', this.templateInfo);
   if (this.templateInfo) {
     if (!this.templateInfo.type) {
       this.templateInfo.type = TEMPLATE_TYPE_NORMAL;
     }
     if (this.templateInfo.type === TEMPLATE_TYPE_NORMAL) {
       await this.installNormalTemplate(); // 安装普通模版
     } else if (this.templateInfo.type === TEMPLATE_TYPE_CUSTOM) {
       // 自定义模版 
       await this.installCustomTemplate();
     } else {
      throw new Error('项目模版类型无法识别');
     }
   } else {
     throw new Error('模版不存在');
   }
  }
  async installNormalTemplate() {
    // 模版缓存的目录
    const templatePath = path.resolve(this.templateNpm.cacheFilePath, 'template');
    // 从缓存目录复制到当前目录
    // const targetPath = path.resolve(process.cwd(), this.projectInfo.projectName);
    const targetPath = process.cwd();
    // console.log(process.cwd(), this.projectName, this.projectInfo, '2222222222222');
    let spinner;
    
    try {
      spinner = ora('正在安装模版...');
      spinner.start();
      // 判断当前目录是否存在
      if (fs.existsSync(templatePath) && fs.existsSync(targetPath)) {
        // 创建当前项目的目录
        const targetPathFile = path.resolve(targetPath, this.projectInfo.projectName);
        if (!fs.existsSync(targetPathFile)) {
          fs.mkdirSync(targetPathFile);
        }
        fse.copySync(templatePath, targetPathFile);
        spinner.succeed('模版安装成功');
      } else {
        spinner.fail('模版安装失败');
        throw new Error('模版安装失败, 模版路径不存在');
      }
      
    } catch (error) {
      spinner.fail('模版安装失败');
      throw new Error(error);
    }
    
  }
  async installCustomTemplate() {
    console.log('installCustomTemplate方法执行了');
  }
  async downloadTemplate() {
    const { projectTemplate } = this.projectInfo
    this.templateInfo = this.npmTemplateList.find(item => item.npmName === projectTemplate);
    const userHome = os.homedir();
    const targetPath = path.resolve(userHome, '.breeze-cli-dev', 'template');
    const storeDir = path.resolve(userHome, '.breeze-cli-dev', 'template', 'node_modules');
    const templateNpmObj = {
      targetPath,
      storeDir,
      packageName: this.templateInfo.npmName,
      packageVersion: this.templateInfo.version,
    }
    const templateNpm = new Package(templateNpmObj);
    let spinner;
    if (templateNpm.exists()) {
      try {
        spinner = ora('正在更新模版...');
        spinner.start();
        await templateNpm.update();
        // await new Promise((resolve) => setTimeout(resolve, 5000))
        spinner.succeed('模版更新成功');
        this.templateNpm = templateNpm; // 存储templateNpm实例，方便后续使用
      } catch (error) {
        spinner.fail('模版更新失败');
        throw new Error(error);
      }
      
    } else {
      try {
        const spinner = ora('正在下载模版...');
        spinner.start();
        await templateNpm.install();
        spinner.succeed('模版下载成功');
        this.templateNpm = templateNpm; // 存储templateNpm实例，方便后续使用
      } catch (error) {
        spinner.fail('模版下载失败');
        throw new Error(error);
      }
      
    }
    // console.log('npm包下载参数', templateNpmObj);
  }
  async prepare() {
    // 判断模版是否存在
    const npmTemplateList = npmTemplate;
    if (!npmTemplateList || npmTemplateList.length === 0) {
      throw new Error('模版不存在');
    }
    this.npmTemplateList = npmTemplateList;
    // 获取当前目录
    const localPath = process.cwd();
    // 判断当前目录是否为空
    // if (!this.isDirEmpty(localPath)) {
    //   let isContinue = false;
    //   if (!this.force) {
    //     const answer = await inquirer.prompt([
    //       {
    //         type: 'confirm',
    //         name: 'isContinue',
    //         message: '当前目录不为空，是否继续创建项目？',
    //         default: false
    //       } 
    //     ])
    //     isContinue = answer.isContinue;
    //     if (!isContinue) {
    //       return;
    //     }
    //   }
    //   if (isContinue || this.force) {
    //     // 利用fs-extra库，判断文件夹是否存在，如果不存在在创建，如果文件夹不为空，则清空文件夹
    //     const confirmDelete = await inquirer.prompt([
    //       {
    //         type: 'confirm',
    //         name: 'isContinue',
    //         message: '是否确认清空当前目录？',
    //         default: false
    //       }
    //     ])
    //     if (confirmDelete.isContinue) {
    //       fse.emptyDirSync(localPath);
    //     }
    //   }
    // }
    return this.getProjectInfo();
  }
  // 获取创建项目信息
  async getProjectInfo() {
    let projectInfo = {}
    function isValidName(v) {
      return /^(@[a-zA-Z0-9-_]+\/)?[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z][a-zA-Z0-9]*|[a-zA-Z0-9])*$/.test(v);
    }
    const { type } = await inquirer.prompt({
      type: 'list',
      name: 'type',
      message: '请选择创建项目类型',
      default: TYPE_PROJECT,
      choices: [
        {
          name: '项目',
          value: TYPE_PROJECT
        },
        {
          name: '组件',
          value: TYPE_COMPONENT
        }
      ],
    })
    log.verbose('type', type);
    const title = type === TYPE_PROJECT ? '项目' : '组件';
    this.npmTemplateList = this.npmTemplateList.filter(item => item.tag.includes(type));
      // 创建项目
      const project = await inquirer.prompt([
        {
          type: 'input',
          name: 'projectName',
          message: `请输入${title}名称`,
          default: this.projectName,
          validate: function (v) {
            if (!isValidName(v)) {
              return `请输入合法的${title}名称`;
            }
            return true;
          },
          filter: function (v) {
            return v;
          }
        },
        {
          type: 'input',
          name: 'version',
          message: `请输入${title}版本号`,
          default: '1.0.0',
          validate: function (v) {
            // 判断版本号是否合法
            if (!valid(v)) {
              return '请输入合法的版本号';
            }
            return true;
          },
          filter: function (v) {
            return valid(v);
          }
        },
        {
          type: 'list',
          name: 'projectTemplate',
          message: `请选择${title}模版`,
          choices: this.createTemplateChoice()
        }
      ])
      const projectName = project.projectName;
      if (this.isCurrentDirNameSame(projectName)) {
        throw new Error(`${title}名称已存在`);
      } else {
        projectInfo = {
          ...project,
          type,
        }
      }
      return projectInfo;
    
  }
  // 判断当前目录是否和项目名称相同
  isCurrentDirNameSame(projectName) {
    // 获取当前目录
    const localPath = process.cwd();
    let fileList = fs.readdirSync(localPath);
    fileList = fileList.filter(file => {
      // 过滤掉.git目录
      return file === projectName;
    });
    return fileList.length > 0;
  }
  isDirEmpty(localPath) {
    // 获取当前目录下的文件
    let fileList = fs.readdirSync(localPath);
    fileList = fileList.filter(file => {
      // 过滤掉.git目录
      return !file.startsWith('.') && ['node_modules'].indexOf(file) < 0;
    });
    console.log('fileList', fileList); 
    return !fileList || fileList.length <= 0;
  }
  createTemplateChoice() {
    return this.npmTemplateList.map((item) => {
      return {
        name: item.name,
        value: item.npmName,
      }
    })
  }
}

function init(argv) {
  // console.log('commands中的init命令执行了', argv );
  return new initCommand(argv);
}

export default init;
